package org.ariadne_eu.hcifetcher.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;

public class AddEnrollmentServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(AddEnrollmentServlet.class
			.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String studentid = req.getParameter("studentid");
		String courseid = req.getParameter("courseid");
		String score = req.getParameter("score");
		int intscore = 0;
		try{
			intscore = Integer.parseInt(score);
		}catch(Exception e){
			//couldn't parse int score
		}
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		Entity enrollment = new Entity("Enrollment");
		enrollment.setProperty("studentid", studentid);
		enrollment.setProperty("courseid", courseid);
		enrollment.setProperty("score",intscore);
		enrollment.setProperty("datestamp", new Date());
		Key k = datastore.put(enrollment);
		resp.getWriter().write("Added enrollment for " + studentid + " to course: " + courseid + " with score: " + intscore + ". Key: " + k);
		log.log(Level.INFO, "Added enrollment for " + studentid + " to course: " + courseid + "with score: " + intscore + ". Key: " + k);
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req,resp);
	}

}
